<?php
class BudgetsController extends AppController {
    var $pageTitle = 'Anggaran';

    function index() {
        $this->paginate['Budget']['order'] = array(
            'Budget.budget_year' => 'ASC',
            'Budget.id' => 'ASC'
        );
        parent::index();
    }

/**
 * Begin method of reports
 */
    function p() {}

    function printhtml() {
        $this->layout = 'printhtml';
        // Configure::write('debug', 0);
        $records = array();

        if ( !empty($this->data) ) {
            $y = $this->data['y']['year'];
            $records = $this->Budget->getTree($y);

            $this->set('year', $y);
            $this->set('records', $records['records']);
            $this->set('total', $records['total']);
            $this->set('total_realization', $records['total_realization']);
            $this->set('total_percent', $records['total_percent']);
            $this->set('total_remain', $records['total_remain']);
            $this->set('unmatch', $records['unmatch']);
            $this->set('total_unmatch', $records['total_unmatch']);
            $this->set('list_unmatch', $records['list_unmatch']);
            $this->set('activities', $records['activities']);
        } else {
            $this->Session->setFlash('Invalid parameter', 'error');
            $this->redirect(array('action'=>'p'));
        }
    }

/**
 * cp only simple composition based on fund_source,
 * cpd add more detail per mak
 */
    function cp() {}
    function cpd() {}

    function cprinthtml() {
        $this->layout = 'printhtml';
        // Configure::write('debug', 0);
        $records = array();

        if ( !empty($this->data) ) {
            $y = $this->data['y']['year'];
            $t = $this->Budget->getComposition($y);

            ClassRegistry::init('Transaction');
            $Transaction = new Transaction;
            $compReal = $Transaction->getCompositionRealizations($y);

            $total = $total_r = $total_remain = 0;
            $percent = $remain = array();
            foreach ($t as $_k => $_t) {
                $percent[$_k] = 0;
                $remain[$_k] = 0;
                // avoid division by zero
                if ( $t[$_k] > 0 ) {
                    $percent[$_k] = ($compReal[$_k]/$t[$_k])*100;
                }
                // remain
                $remain[$_k] = $t[$_k] - $compReal[$_k];

                $total += $t[$_k]; // total budget
                $total_r += $compReal[$_k]; // total realization
                $total_remain += $remain[$_k]; // total remaining
            }
            $total_percent = ($total_r/$total)*100;

            $this->set('year', $y);
            $this->set('t', $t); // budget
            $this->set('real', $compReal); // realization
            $this->set('remain', $remain); // remaining
            $this->set('percent', $percent); // percentage
            $this->set('total', $total);
            $this->set('total_r', $total_r);
            $this->set('total_remain', $total_remain);
            $this->set('total_percent', $total_percent);
        } else {
            $this->Session->setFlash('Invalid parameter', 'error');
            $this->redirect(array('action'=>'p'));
        }
    }

    function cpdprinthtml() {
        $this->layout = 'printhtml';
        // Configure::write('debug', 0);
        $records = array();

        if ( !empty($this->data) ) {
            $y = $this->data['y']['year'];
            // belanja pegawai
            $t = $this->Budget->getCompositionDetail($y);

            // define mak
            $t1 = array(
                /*
                'Gaji' => array(
                    '00001' => array(
                        '511111', '511129',
                        '511119', '511121', '511122', '511124',
                        '511125', '511126', '511151'
                    )
                ),*/
                'Gaji' => array(
                        '511111', '511129',
                        '511119', '511121', '511122', '511124',
                        '511125', '511126', '511151'
                ),
                /*
                'Lembur' => array(
                    '00001' => array(
                        '512211'
                    )
                ),*/
                'Lembur' => array('512211'),
                /*
                'Vakasi' => array(
                    '00001' => array(
                        '512311'
                    )
                ),*/
                'Vakasi' => array(
                    '512311'
                ),
                /*
                'Honor Dosen TT' => array(
                    '00001' => array(
                        '512111'
                    )
                )*/
                'Honor Dosen TT' => array(
                    '512111'
                )
            );
            $t1_t = array(
                'Gaji' => 0, 'Lembur' => 0,
                'Vakasi' => 0, 'Honor Dosen TT' => 0
            );

            $t2 = array(
                //'Rehab Asrama'=> array('01139'),
                /*
                'Gedung dan Bangunan' => array(
                    'A' => array(
                        '533111'
                    ),
                    'B' => array(
                        '533111'
                    )
                ),*/
                'Gedung dan Bangunan' => array(
                    '533111'
                ),
                //'Pembangunan Gedung' => array('00165'),
                //'Pembangunan Gedung, Mebele Air' => array('533111'),
                //'Mebeleair' => array('00273'),
                //'Alat Pendidikan' => array('00274'),
                /*
                'Peralatan dan Mesin' => array(
                    'A' => array('532111'),
                    'B' => array('532111'),
                ),*/
                'Peralatan dan Mesin' => array(
                    '532111'
                ),
                //'Sepeda Motor' => array('00289'),
                //'Sepeda Motor' => array('532111'),
                //'Buku Perpustakaan' => array('00009'),
                /*
                'Buku Perpustakaan' => array(
                    '00009' => array(
                        '521219', '536111', '521213'
                    )
                ),
                */
                'Buku Perpustakaan' => array('536111')
                //'Infrastruktur jaringan internet' => array('00040'),
                //'Infrastruktur jaringan internet' => array('532111'),
            );
            $t2_t = array(
                'Gedung dan Bangunan' => 0,
                'Peralatan dan Mesin' => 0,
                'Buku Perpustakaan' => 0
            );

            $t3 = array(
                /*
                'Honor' => array(
                    '00026' => array('521115'),
                    '04863' => array('521115'),
                    '00016' => array('521115'),
                    '00094' => array('521115'),
                    '00012' => array('521213'),
                    '00029' => array('521213'),
                    'A'     => array('521213', '522115'),
                    'B'     => array('521213', '522115'),
                    'C'     => array('521213', '522115'),
                    'D'     => array('521213', '522115'),
                    '00119' => array('521213', '522115'),
                    '00538' => array('521213', '522115'),
                    '00009' => array('521213'),
                    '04245' => array('521213', '522115'),
                    '02164' => array('521213'),
                    '04235' => array('521213')
                )
                */
                'Honor' => array('521115', '521213', '522115'),
                'Operasional' => array(
                    '521119', '521111', '523111',
                    '523121', '522111', '521219',
                    '521113', '522114'
                ),
                'Perjalanan' => array(
                    '524111', '524119'
                ),
                'Bahan' => array(
                    '521211'
                )

            );
            $t3_t = array(
                'Honor' => 0, 'Operasional' => 0, 'Perjalanan' => 0,
                'Bahan' => 0
            );
            $total = array(
                1 => array('values' => 0, 'label' => 'A. Belanja Pegawai'),
                2 => array('values' => 0, 'label' => 'B. Belanja Modal'),
                3 => array('values' => 0, 'label' => 'C. Belanja Barang')
            );
            $totals = 0;

            ClassRegistry::init('Activity');

            /*
            foreach ($t as $_k => $_t) {
                for ($i = 1; $i <= 3; $i++) {
                    foreach (${'t'.$i} as $__k => $__t) {
                        foreach ($__t as $___k => $___t) {

                            if ( is_array($___t) && $A[$_k] == $___k ) {
                                foreach ($___t as $____t) {
                                    foreach ($_t as $_k_ => $_t_) {
                                        if ( $____t == $_k_ ) {
                                            ${'t'.$i.'_t'}[$__k] += $_t_;
                                            $total[$i]['values'] += $_t_;
                                            $totals += $_t_;
                                        }
                                    }
                                }
                            } else if ($A[$_k] == $___k) {
                                pr($___t);
                                /*
                                $_t_ = $_t;
                                foreach ($_t_ as $_k_ => $_t__) {
                                    if ( $___t == $_k_ ) {
                                        $_t__ = $this->Budget->getTotalByMAK($___t);
                                        ${'t'.$i.'_t'}[$__k] += $_t__;
                                        $total[$i]['values'] += $_t__;
                                        $totals += $_t__;
                                    }
                                }*/
                                /*
                            }
                        }
                        */
                        // reverse values to keys

                        //pr($__t); die;
                        /*
                        $__tr = array_flip($__t);

                        if ( array_key_exists($_k, $__tr) ) {
                            ${'t'.$i.'_t'}[$__k] += $_t;
                            $total[$i]['values'] += $_t;
                            $totals += $_t;
                        }
                        */ /*
                    }
                }
            }die;*/

            // tx_t
            for ($i = 1; $i <= 3; $i++) {
                foreach (${'t'.$i} as $k => $v) {
                    ${'t'.$i.'_t'}[$k] = $this->Budget->getTotalByMAK($v);
                    $total[$i]['values'] += ${'t'.$i.'_t'}[$k];
                    $totals += ${'t'.$i.'_t'}[$k];
                }
            }

            ClassRegistry::init('Transaction');
            $Transaction = new Transaction;
            //$R = $Transaction->getRealizationMAK($y);
            $R = $Transaction->getRealizationMAKForComposition($y);

            $totalR = $R1 = $R2 = $R3 = $P1 = $P2 = $P3 = array();
            $totalsR = 0;
            // we need to reverse activity
            /*
            $A = array_flip($A);
            for ($i = 1; $i <= 3; $i++) {
                // define first
                foreach (${'t'.$i.'_t'} as $__k => $__t) {
                    ${'R'.$i}[$__k] = 0;
                }
                $totalR[$i] = 0;

                foreach (${'t'.$i} as $__k => $__t) {
                    foreach ($__t as $___k => $___t) {
                        if ( is_array($___t) ) {
                            foreach ($___t as $____k => $____t) {
                                if ( isset($A[$___k]) && isset($R[ $A[$___k] ][$____t]) ) {
                                    ${'R'.$i}[$__k] += $R[ $A[$___k] ][$____t];
                                    $totalR[$i] += $R[ $A[$___k] ][$____t];
                                }
                            }
                        }
                        ${'P'.$i}[$__k] = ${'t'.$i.'_t'}[$__k] ? (${'R'.$i}[$__k]/${'t'.$i.'_t'}[$__k])*100 : 0;
                    }
                }

                $totalsR += $totalR[$i];
            }
            */

            $RR = array_keys($R);

            for ($i = 1; $i <= 3; $i++) {
                // define first
                foreach (${'t'.$i.'_t'} as $__k => $__v) {
                    ${'R'.$i}[$__k] = 0;
                }
                $totalR[$i] = 0;

                foreach (${'t'.$i} as $k => $v) {
                    foreach ( $v as $_v ) {
                        if ( in_array($_v, $RR) ) {
                            ${'R'.$i}[$k] += $R[$_v];
                            $totalR[$i] += $R[$_v];
                        }
                    }
                    ${'P'.$i}[$k] = ${'t'.$i.'_t'}[$k] ?
                        (${'R'.$i}[$k]/${'t'.$i.'_t'}[$k])*100 : 0;
                }

                $totalsR += $totalR[$i];
            }

            $this->set('t1', $t1_t);
            $this->set('t2', $t2_t);
            $this->set('t3', $t3_t);
            $this->set('total', $total);
            $this->set('totals', $totals);
            $this->set('R1', $R1);
            $this->set('R2', $R2);
            $this->set('R3', $R3);
            $this->set('totalR', $totalR);
            $this->set('totalsR', $totalsR);
            $this->set('P1', $P1);
            $this->set('P2', $P2);
            $this->set('P3', $P3);
            $this->set('year', $y);
        } else {
            $this->Session->setFlash('Invalid parameter', 'error');
            $this->redirect(array('action'=>'p'));
        }
    }

    function budgetvsreal() {
        $group = $this->Session->read('Group.Group');
        if ( preg_match('/^pudir(1|3|4)$/', $group['name']) ) {
            $code = '05';
            switch ($group['name']) {
                case 'pudir1': $code = '05'; break;
                case 'pudir3': $code = '06'; break;
                case 'pudir4': $code = '07'; break;
            }
            $u = $this->Budget->UnitCode->find('list', array(
                'conditions' => array('UnitCode.code' => $code)
            ));
        } else {
            $u = $this->Budget->UnitCode->find('list');
            $u['@pudir2'] = 'Pudir 2';
            $u['@all'] = 'All';
        }
        $this->set('unit_codes', $u);
    }

    function budgetvsrealprinthtml() {
        $this->layout = 'printhtml';
        // Configure::write('debug', 0);
        $records = array();

        if ( !empty($this->data) ) {
            $y = $this->data['y']['year'];
            $u = $this->data['Budget']['unit_code_id'];

            if ($u == '@all') {
                $records = $this->getAllBudgetAndRealizations($y);
                $total = $total_r = $total_remain = $total_percent = 0;

                // TODO: remove this hardcode
                // for Subbag.*
                $pudir2 = array(
                    'budget' => 0, 'realization' => 0,
                    'remain' => 0, 'percent' => 0
                );
                foreach ($records as $key => $record) {
                    $total += $record['budget'];
                    $total_r += $record['realization'];
                    $total_remain += $record['remain'];

                    if ( substr($key, 0, 7) == 'Subbag.' ) {
                        $pudir2['budget'] += $record['budget'];
                        $pudir2['realization'] += $record['realization'];
                        $pudir2['remain'] += $record['remain'];
                    }
                }
                $pudir2['percent'] =
                    ($pudir2['realization']/$pudir2['budget'])*100;
                array_splice($records, 8, 0, array($pudir2));

                // TODO: remove this hardcode
                // unset Subbag.*
                unset($records['Subbag.Keuangan']);
                unset($records['Subbag.TL&Kepeg.']);
                unset($records['Subbag.Umum']);

                $total_percent = ($total_r/$total)*100;
                $this->set('year', $y);
                $this->set('t', $records);
                $this->set('u', 'Daya Serap Anggaran PoliMedia');
                $this->set('total', $total);
                $this->set('total_r', $total_r);
                $this->set('total_remain', $total_remain);
                $this->set('total_percent', $total_percent);
                $this->render('budgetvsrealprinthtml_all');

            } else if ($u == '@pudir2') {
                // TODO: remove this hardcode
                // umum
                $r1 = $this->getRealizationAndBudget(2, $y);
                // kepeg
                $r2 = $this->getRealizationAndBudget(3, $y);
                // keu
                $r3 = $this->getRealizationAndBudget(4, $y);

                $this->set('year', $y);
                $this->set('u', 'Pudir II');
                $total = $total_r = $total_remain = $total_percent = 0;
                for ($i = 1; $i <= 3; $i++) {
                    $this->set('t'.$i, ${'r'.$i}['records']);
                    $this->set('total'.$i, ${'r'.$i}['total']);
                    $this->set('total_r'.$i, ${'r'.$i}['total_r']);
                    $this->set('total_remain'.$i, ${'r'.$i}['total_remain']);
                    $this->set('total_percent'.$i, ${'r'.$i}['total_percent']);
                    $total += ${'r'.$i}['total'];
                    $total_r += ${'r'.$i}['total_r'];
                }
                $total_remain = $total - $total_r;
                $total_percent = ($total_r/$total)*100;

                $this->set('total', $total);
                $this->set('total_r', $total_r);
                $this->set('total_remain', $total_remain);
                $this->set('total_percent', $total_percent);
                $this->render('budgetvsrealprinthtml_pudir2');
            } else {
                $r = $this->getRealizationAndBudget($u, $y);

                $this->set('year', $y);
                $this->set('u', $r['uname']);
                $this->set('t', $r['records']);
                $this->set('total', $r['total']);
                $this->set('total_r', $r['total_r']);
                $this->set('total_remain', $r['total_remain']);
                $this->set('total_percent', $r['total_percent']);
            }
        } else {
            $this->Session->setFlash('Invalid parameter', 'error');
            $this->redirect(array('action'=>'p'));
        }
    }

/**
 * Select year of absorption
 */
    function absorptionform($specific = null) {
        $param = '';
        if ( $specific ) {
            $param = '/' . $specific;
        }
        $this->set('specific', $param);
    }

/**
 * Graphic of absorption
 */
    function absorption($specific = null) {
        // Configure::write('debug', 0);
        $records = array();

        if ( !empty($this->data) ) {
            $this->helpers[] = 'chart';

            $y = $this->data['y']['year'];
            $records = $this->getAllBudgetAndRealizations($y, $specific);
            //pr($records);
            //die;
            $data = array();
            $budgets = array('values' => array(), 'name' => 'Anggaran');
            $realizations = array('values' => array(), 'name' => 'Realisasi');
            $pudir2 = array(
                'budget' => 0, 'realization' => 0
            ); // combine Subbag.*
            $i = 0;
            // array of removed / unseted keys,
            // actually key with Subbag.*
            $removes = array();
            foreach ($records as $k => $r) {
                $budgets['values'][$k] = $r['budget'];
                $realizations['values'][$k] = $r['realization'];

                // combine into pudir2
                // when no $specific passed
                if ( substr($k,0,7) == 'Subbag.' && !$specific ) {
                    $pudir2['budget'] += $r['budget'];
                    $pudir2['realization'] += $r['realization'];
                    $removes[$k] = $k;
                }

                $i++;
            }

            if ( !$specific ) {
                // index position to insert Pudir II
                $pos = 8;
                // init array after $pos
                $end_realizations = $end_budgets = array();

                $end_realizations = array_splice($realizations['values'], $pos);
                $end_budgets =  array_splice($budgets['values'], $pos);

                $realizations['values'] = array_merge(
                    $realizations['values'], array(
                        'Pudir II' => $pudir2['realization']
                    )
                );
                $realizations['values'] = array_merge(
                    $realizations['values'], $end_realizations
                );
                $budgets['values'] = array_merge(
                    $budgets['values'], array(
                        'Pudir II' => $pudir2['budget']
                    )
                );
                $budgets['values'] = array_merge(
                    $budgets['values'], $end_budgets
                );

                // unset Subbag.*
                // that resided in $removes
                foreach ($removes as $remove) {
                    unset($budgets['values'][$remove]);
                    unset($realizations['values'][$remove]);
                }
            }

            $data = array($budgets, $realizations);
            $this->set('data', $data);

            $options = array();
            $options['type'] = 'bar';
            $options['month'] = false;
            $options['title'] = 'Grafik Daya Serap Anggaran ' . $y;

            if ( $specific == 'pudir2' ) {
                $options['title'] = 'Grafik Daya Serap Anggaran Pudir II ' . $y;
            }
            $this->set('specific', $specific);

            $options['shadow'] = true;
            $options['threshold'] = array('showLabel' => true);
            $options['label'] = array('max' => false, 'min' => false);
            $options['x'] = 'Unit Kerja';
            $options['y'] = 'Anggaran dan Realisasi';
            $options['filename'] = 'absorption_' .
                $this->Auth->user('id') . '_' . time() .
                '.png';
            $options['stroke'] = false;
            $this->set('options', $options);

        } else {
            $this->Session->setFlash('Invalid parameter', 'error');
            $this->redirect(array('action'=>'p'));
        }
    }

/**
 * get all budget and realizations from all units
 * for particular year
 * @param mixed $year year of transactions
 */
    function getAllBudgetAndRealizations($year, $specific = null) {
        $y = $year;
        $this->Budget->Behaviors->attach('Containable');
        $records = array();
        $conditions = array(
            'Budget.budget_year' => $y
        );

        if ($specific == 'pudir2') {
            $conditions['Budget.unit_code_id'] = array(2,3,4);
        }

        // get budget based on budget year
        // and unit code
        $t = $this->Budget->find('all', array(
            'conditions' => $conditions,
            'order' => 'UnitCode.name ASC',
            'fields' => array(
                'Budget.unit_code_id', 'Budget.budget_year'
            ),
            'contain' => array(
                'UnitCode' => array(
                    'fields' => array('name')
                ),
                'BudgetDetail' => array(
                    'fields' => array('id'),
                    'BudgetDetailDescription' => array(
                        'fields' => array(
                            'unit_count', 'unit_amount'
                        )
                    )
                )
            )
        ));

        // get realization from transaction
        // based on transaction date and unit code
        ClassRegistry::init('Transaction');
        $Transaction = new Transaction;
        $z = $Transaction->getRealizations($y, $specific);

        foreach ($t as $_kt => $_t) {
            if (!isset($records[$_t['UnitCode']['name']])) {
                $records[$_t['UnitCode']['name']] = array();
            }

            foreach ($_t['BudgetDetail'] as $__kt => $__t) {
                if (!isset($records[$_t['UnitCode']['name']]['budget'])) {
                    $records[$_t['UnitCode']['name']]['budget'] = 0;
                }
                foreach ( $__t['BudgetDetailDescription'] as $___kt => $___t) {
                    $records[$_t['UnitCode']['name']]['budget'] +=
                        $___t['unit_count']*$___t['unit_amount'];
                }
            }

            // realization
            $records[$_t['UnitCode']['name']]['realization'] = 0;
            if ( isset($z[$_t['UnitCode']['id']]) ) {
                foreach ( $z[$_t['UnitCode']['id']] as $_zk => $_z ) {
                    $records[$_t['UnitCode']['name']]['realization']
                    += $_z;
                }
            }

            // percentage
            $records[$_t['UnitCode']['name']]['percent'] = 0;
            if ( $records[$_t['UnitCode']['name']]['budget'] > 0 ) {
                $records[$_t['UnitCode']['name']]['percent'] =
                ($records[$_t['UnitCode']['name']]['realization'] /
                    $records[$_t['UnitCode']['name']]['budget'])*100;
            }

            // remain
            $records[$_t['UnitCode']['name']]['remain'] = 0;
            $records[$_t['UnitCode']['name']]['remain'] =
                $records[$_t['UnitCode']['name']]['budget'] -
                $records[$_t['UnitCode']['name']]['realization'];

        }

        return $records;
    }

/**
 * Get realization and budget for particular unit and year
 * @param int $unit_code_id id of unit_code
 * @year mixed $year year of transactions
 * @return array $ret
 */
    function getRealizationAndBudget($unit_code_id, $year) {
        $u = $unit_code_id;
        $y = $year;
        $this->Budget->Behaviors->attach('Containable');

        // get budget based on budget year
        // and unit code
        $t = $this->Budget->find('all', array(
            'conditions' => array(
                'Budget.unit_code_id' => $u,
                'Budget.budget_year' => $y
            ),
            'fields' => array(
                'Budget.unit_code_id', 'Budget.budget_year',
                'Budget.activity_id'
            ),
            'contain' => array(
                'Activity' => array(
                    'fields' => array(
                        'name'
                    )
                ),
                'UnitCode' => array(
                    'fields' => array('name')
                ),
                'BudgetDetail' => array(
                    'fields' => array('id'),
                    'BudgetDetailDescription' => array(
                        'fields' => array(
                            'unit_count', 'unit_amount'
                        )
                    )
                )
            )
        ));

        // unit code name
        $uname = $t[0]['UnitCode']['name'];

        // get realization from transaction
        // based on transaction date and unit code
        ClassRegistry::init('Transaction');
        $Transaction = new Transaction;
        $z = $Transaction->getRealization($u, $y);

        $records = array();
        $total = 0; // total budget
        $total_r = 0; // total realization
        $total_remain = 0; // total of budget remaining
        $total_percent = 0; // total percentage
        foreach ($t as $_kt => $_t) {
            $records[$_kt]['no'] = $_kt+1;
            $records[$_kt]['activity'] = $_t['Activity']['name'];

            // sum  budget
            $records[$_kt]['budget'] = 0;
            foreach ($_t['BudgetDetail'] as $__kt => $__t) {
                foreach ( $__t['BudgetDetailDescription'] as $___kt => $___t) {
                    $records[$_kt]['budget'] +=
                        $___t['unit_count']*$___t['unit_amount'];
                }
            }
            // total budget
            $total += $records[$_kt]['budget'];

            // sum realization
            $records[$_kt]['realization'] = 0;
            if ( isset($z[ $_t['Activity']['id'] ]) ) {
                $records[$_kt]['realization'] = $z[ $_t['Activity']['id'] ];
            }

            // prosentase
            $records[$_kt]['percent'] = 0;
            if ($records[$_kt]['budget'] > 0) {
            $records[$_kt]['percent'] =
                ($records[$_kt]['realization']/$records[$_kt]['budget'])
                *100;
            }
            // total percentage
            $total_percent += $records[$_kt]['percent'];

            // remaining budget
            $records[$_kt]['remain'] =
                $records[$_kt]['budget']-$records[$_kt]['realization'];
            // total remaining budget
            $total_remain += $records[$_kt]['remain'];

            // total realization
            $total_r += $records[$_kt]['realization'];
        }
        $total_percent = $total_percent / sizeof($t);

        return compact(
            'records',
            'total', 'total_r', 'uname',
            'total_remain', 'total_percent'
        );
    }
/**
 * EOF method of reports
 */


    function add() {
        $this->__setAdditionals();
		$this->__saving();
	}

    function edit($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
			$this->__redirect();
        }
		$this->set('id', $id);

        $this->__setAdditionals(1, $id);

        $this->__saving(1, $id);

		if (empty($this->data)) {
			$this->data = $this->{$this->modelName}->find('first', array(
                'conditions' => array(
                    $this->modelName . '.id' => $id
                )
            ));

            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect('index');
            }
		} else {
            $this->data[$this->modelName]['id'] = $id;
        }
    }

    function __saving($edit = false, $id = null) {
        if ( !empty($this->data) ) {
			$messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __('successfully added', true);
			$messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __('cannot add this new record. Please fix the errors mentioned belows', true);
            if ( $edit ) {
                $messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("successcully edited", true);
                $messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("cannot save this modification. Please fix the errors mentioned belows", true);
            }

            if ( $edit ) {
                $this->Budget->id = $id;
            } else {
                $this->Budget->create();
            }
            $budgets = $this->data;

			if ($this->Budget->save($this->data)) {

                // on editing we need to delete all
                // budget_detail and descriptions
                // whose budget id is $id
                if ( $edit && $id ) {
                    // get created_by, since
                    // we are delete all children
                    $created_by = $this->Budget->find('first', array(
                        'conditions' => array(
                            'Budget.id' => $id
                        ),
                        'fields' => array('Budget.created_by'),
                        'recursive' => -1
                    ));
                    $created_by = $created_by['Budget']['created_by'];

                    $this->Budget->BudgetDetail->deleteAll(
                        array('BudgetDetail.budget_id' => $id),
                        true,
                        true
                    );
                }

                // set budget_id, created_by and modified_by
                foreach ( $this->data['Budget']['BudgetDetail'] as $key => $bd ) {
                    $this->data['Budget']['BudgetDetail'][$key]['budget_id'] = $this->Budget->id;
                    if ( isset($this->data['Budget']['created_by']) ) {
                        $this->data['Budget']['BudgetDetail'][$key]['created_by'] = $this->data['Budget']['created_by'];
                        $this->data['Budget']['BudgetDetail'][$key]['modified_by'] = $this->data['Budget']['created_by'];
                    }

                    if ( isset($this->data['Budget']['modified_by']) ) {
                        $this->data['Budget']['BudgetDetail'][$key]['created_by'] = $created_by;
                        $this->data['Budget']['BudgetDetail'][$key]['modified_by'] = $this->data['Budget']['modified_by'];
                    }

                    // save detail one by one
                    $this->Budget->BudgetDetail->create();

                    if ( $this->Budget->BudgetDetail->save(
                        $this->data['Budget']['BudgetDetail'][$key]) ) {

                        // set budget detail_id, created_by or modified_by
                        // on BudgetDetailDescription
                        foreach ( $this->data['Budget']['BudgetDetail']
                            [$key]['BudgetDetailDescription'] as $key2 => $bdd ) {

                            $this->data['Budget']['BudgetDetail']
                                [$key]['BudgetDetailDescription']
                                [$key2]['budget_detail_id'] = $this->Budget->BudgetDetail->id;

                            if ( isset($this->data['Budget']['created_by']) ) {
                                $this->data['Budget']['BudgetDetail']
                                    [$key]['BudgetDetailDescription']
                                    [$key2]['created_by'] = $this->data['Budget']['created_by'];
                                $this->data['Budget']['BudgetDetail']
                                    [$key]['BudgetDetailDescription']
                                    [$key2]['modified_by'] = $this->data['Budget']['created_by'];
                            }

                            if ( isset($this->data['Budget']['modified_by']) ) {
                                $this->data['Budget']['BudgetDetail']
                                    [$key]['BudgetDetailDescription']
                                    [$key2]['modified_by'] = $this->data['Budget']['modified_by'];
                                $this->data['Budget']['BudgetDetail']
                                    [$key]['BudgetDetailDescription']
                                    [$key2]['created_by'] = $created_by;
                            }

                            // remove thousand separator
                            $this->data['Budget']['BudgetDetail']
                                    [$key]['BudgetDetailDescription']
                                    [$key2]['unit_count'] = str_replace(',', '', $this->data['Budget']['BudgetDetail']
                                        [$key]['BudgetDetailDescription']
                                        [$key2]['unit_count']
                                    );
                            $this->data['Budget']['BudgetDetail']
                                    [$key]['BudgetDetailDescription']
                                    [$key2]['unit_amount'] = str_replace(',', '', $this->data['Budget']['BudgetDetail']
                                        [$key]['BudgetDetailDescription']
                                        [$key2]['unit_amount']
                                    );
                        }

                        // save all description per each detail_id
                        $this->Budget->BudgetDetail->BudgetDetailDescription->create();
                        if  ( $this->Budget->BudgetDetail->BudgetDetailDescription->saveAll($this->data['Budget']['BudgetDetail'][$key]['BudgetDetailDescription']) ) {
                            // oke

                        } else { // failed savingAll description
                            $this->set('budgets', $budgets['Budget']);
                            $this->Session->setFlash($messageFlashError, 'error');
                        }

                    // eof saving detail
                    } else { // failed saving budget_detail
                        $this->set('budgets', $budgets['Budget']);
                        $this->Session->setFlash($messageFlashError, 'error');
                    }

                } // eof set budget_id

                $this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->__redirect();

			} else {
                $this->set('budgets', $budgets['Budget']);
                $this->Session->setFlash($messageFlashError, 'error');
			}
		}
    }

    function __setAdditionals($edit = false, $id = null) {
        // kegiatan
        $activities = $this->Budget->Activity->generatetreelist();
        $activities__ = array();
        foreach ($activities as $kactv => $actv) {
            if ( $this->Budget->Activity->childcount($kactv, true) > 0 ) {
                $activities__[$kactv] = $actv;
            }
        }
        $this->set('activities', $activities__);

        $subactivities = array();
        $activity_id = null;
        $parent_id = null;
        if ( isset($this->data['Budget']['activity_id']) ) {
            $subactivities = $activities;
            $activity_id = $this->data['Budget']['activity_id'];
        }

        if ( $edit ) {
            $a = $this->Budget->find('first', array(
                'conditions' => array(
                    'Budget.id' => $id
                ),
                'fields' => array('Activity.id', 'Activity.parent_id'),
                'contains' => array('Activity')
            ));
            $activity_id = $a['Activity']['id'];
            $parent_id = $a['Activity']['parent_id'];

            // get list of activities that has same parent
            $subactivities = $this->Budget->Activity->find('list', array(
                'conditions' => array(
                    'Activity.parent_id' => $parent_id
                )
            ));

            // get budgets
            $this->Budget->Behaviors->attach('Containable');
            $budgets = $this->Budget->find('first', array(
                'conditions' => array(
                    'Budget.id' => $id
                ),
                'contain' => array(
                    'BudgetDetail' => array(
                        'BudgetDetailDescription' => array(
                            'order' => 'BudgetDetailDescription.id ASC'
                        ),
                        'order' => 'BudgetDetail.id ASC'
                    )
                ),
                'order' => 'Budget.id ASC'
            ));
            $this->set('budgets', $budgets);
        }

        $this->set('subactivities', $subactivities);
        $this->set('activity_id', $activity_id);
        $this->set('parent_id', $parent_id);

        // mak
        $activity_children = array();
        $ac = $this->Budget->BudgetDetail->ActivityChild->find('all');
        foreach ( $ac as $c ) {
            $activity_children[ $c['ActivityChild']['id'] ] = $c['ActivityChild']['name'] .
                ' (' . $c['ActivityChild']['code'] . ')';
        }
        $this->set('activity_children', $activity_children);

        //
        $volumes = $this->Budget->BudgetDetail->BudgetDetailDescription->Volume->find('list');
        $this->set('volumes', $volumes);

        $unit_codes = $this->Budget->UnitCode->find('list');
        $this->set('unit_codes', $unit_codes);

        $fund_sources = array(
            'bind' => 'Mengikat',
            'unbind' => 'Tidak Mengikat',
            'pnbp' => 'PNBP'
        );
        $this->set('fund_sources', $fund_sources);

        // set ajax URL
        $prefix = parent::__pathToController() . '/getOptions';
        $this->set('ajaxURL', "var ajaxURL = '" . $prefix . "'; var imgLoading = '" . $this->webroot . "img/loading.gif';");
    }
}
?>
